<template>
  <div class="dataVisualize-box">
    <div class="card box">
      <el-tabs v-model="tabActive" class="demo-tabs">
        <el-tab-pane v-for="item in tab" :key="item.name" :label="item.label" :name="item.name"></el-tab-pane>
      </el-tabs>
      <slot></slot>
      <div class="content-wrapper">
        <v3-drag-zoom-container class="content" :loading="isLoading" :min-zoom="0.8" ref="zoomContainer" :draggable="draggable">
          <canvas v-if="!isLoading && !isError" ref="imageCanvas" class="canvas-box"></canvas>
          <div v-if="isError" class="error-message">Failed to load image</div>
        </v3-drag-zoom-container>

        <!-- 添加图例 -->
        <div v-if="showLegend" class="legend-container">
          <div class="legend-item">
            <span class="color-block red"></span>
            <span class="legend-text">市场占比: [0,30)</span>
          </div>
          <div class="legend-item">
            <span class="color-block orange"></span>
            <span class="legend-text">市场占比: [30,40)</span>
          </div>
          <div class="legend-item">
            <span class="color-block yellow"></span>
            <span class="legend-text">市场占比: [40,50)</span>
          </div>
          <div class="legend-item">
            <span class="color-block green"></span>
            <span class="legend-text">市场占比: [50,60)</span>
          </div>
          <div class="legend-item">
            <span class="color-block blue"></span>
            <span class="legend-text">市场占比: [60,100]</span>
          </div>
        </div>
      </div>
      <div class="action-btn map-set">
        <!-- 放大按钮 -->
        <div class="action-item location" @mousedown="startZooming('1')" @mouseup="stopZooming" @mouseleave="stopZooming">
          <el-button type="primary" circle size="default" :icon="ZoomIn"></el-button>
        </div>
        <!-- 缩小按钮 -->
        <div class="action-item location" @mousedown="startZooming('2')" @mouseup="stopZooming" @mouseleave="stopZooming">
          <el-button type="primary" circle size="default" :icon="ZoomOut"> </el-button>
        </div>
        <!-- 重置按钮 -->
        <div class="action-item location" @click="drawAreaSet('3')">
          <el-button type="primary" circle size="default" :icon="Aim"> </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { GetIMAGE } from "@/api/modules/upload";
import { ZoomIn, ZoomOut, Aim } from "@element-plus/icons-vue";

const tabActive = ref(1);
const src = ref<string | undefined>(undefined);
const isLoading = ref(true);
const isError = ref(false);
const timeout = 5000; // 设置超时时间为5秒
const zoomContainer: any = ref(null);
let zoomInterval: any = null; // 定时器引用
const draggable = ref(true);

const props = defineProps({
  tab: {
    type: Array as () => any[],
    default: () => []
  },
  showLegend: {
    type: Boolean,
    default: false
  }
});

const selectedTab = computed(() => props.tab.find(item => item.name === tabActive.value));

const loadImage = async (tabName: object) => {
  try {
    isLoading.value = true;
    isError.value = false;

    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);

    const res: any = await GetIMAGE(tabName);
    clearTimeout(id);

    src.value = URL.createObjectURL(new Blob([res], { type: "image/png" }));
  } catch (error: any) {
    if (error.name === "AbortError") {
      console.error("Image loading timeout:", error);
      isError.value = true;
    } else {
      console.error("Image loading error:", error);
      isError.value = true;
    }
  } finally {
    isLoading.value = false;
  }
};

const drawImageOnCanvas = () => {
  const canvas = document.querySelector("canvas") as HTMLCanvasElement;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  const img = new Image();
  img.src = src.value || "";

  img.onload = () => {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
  };
};

const drawAreaSet = async (type: string) => {
  if (type === "1") zoomContainer.value.zoom(0.1);
  if (type === "2") zoomContainer.value.zoom(-0.1);
  if (type === "3") zoomContainer.value.reset();
};

const startZooming = (type: string) => {
  if (type === "1" || type === "2") {
    zoomInterval = setInterval(() => {
      drawAreaSet(type);
    }, 100); // 每100毫秒调整一次
  }
};

const stopZooming = () => {
  if (zoomInterval) {
    clearInterval(zoomInterval);
    zoomInterval = null;
  }
};

watch(
  () => selectedTab.value,
  async newTabName => {
    if (newTabName) {
      await loadImage(newTabName);
      zoomContainer.value.reset();
      nextTick(() => drawImageOnCanvas()); // Ensure DOM update before drawing
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
